package com.cmw.auntapp.core.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;


import com.cmw.auntapp.core.util.log.LogUtil;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.RequiresApi;

/**
 * 
 * @version 1.0
 */
public class AppTools {
    private static final String TAG = "AppTools";
    private static long lastTime;

    public static final int RESULT_ZOOM = 11;

    /**
     * 获取当前应用的 SHA1 值。
     * 百度或高德SDK 要通过此 SHA1 值生成API KEY
     *
     * @param context
     * @return 返回SHA1 值
     */
    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = null;
            md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            //result即为获取的SHA1值,如果最后面有冒号的话就去掉
            Log.i(TAG,result.toString());
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Intent getAppOpenIntentByPackageName(Context context,String packageName){
        //Activity完整名
        String mainAct = null;
        //根据包名寻找
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED|Intent.FLAG_ACTIVITY_NEW_TASK);

        @SuppressLint("WrongConstant")
        List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (StringUtils.isEmpty(mainAct)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        return intent;
    }

    public static Context getPackageContext(Context context, String packageName) {
        Context pkgContext = null;
        if (context.getPackageName().equals(packageName)) {
            pkgContext = context;
        } else {
            // 创建第三方应用的上下文环境
            try {
                pkgContext = context.createPackageContext(packageName,
                        Context.CONTEXT_IGNORE_SECURITY
                                | Context.CONTEXT_INCLUDE_CODE);
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return pkgContext;
    }

    /**
     * 检测一个android程序是否在运行
     * @param context
     * @param PackageName
     * @return
     */
    public static  boolean isServiceStarted(Context context,String PackageName) {
        //<uses-permission android:name="android.permission.GET_TASKS"/>
        //https://crazier9527.iteye.com/blog/1476134
        boolean isStarted =false;
        try {
            ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            int intGetTastCounter = 1000;
            List<ActivityManager.RunningServiceInfo> mRunningService = mActivityManager.getRunningServices(intGetTastCounter );
            for (ActivityManager.RunningServiceInfo amService : mRunningService) {
                if(0 == amService.service.getPackageName().compareTo(PackageName)) {
                    isStarted = true;
                    break;
                }
            }
        }
        catch(SecurityException e) {
            e.printStackTrace();
        }
        return isStarted;
    }


    /**
     * 打开第三方包 APP
     * @param context
     * @param packageName
     * @return
     */
    public static boolean openPackage(Context context, String packageName) {
        Context pkgContext = getPackageContext(context, packageName);
        Intent intent = getAppOpenIntentByPackageName(context, packageName);
        if (pkgContext != null && intent != null) {
            pkgContext.startActivity(intent);
            return true;
        }
        return false;
    }


    public static void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
                    MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    public static Bitmap toGrayscale(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        Bitmap faceIconGreyBitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(faceIconGreyBitmap);
        Paint paint = new Paint();
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0);
        ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
                colorMatrix);
        paint.setColorFilter(colorMatrixFilter);
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return faceIconGreyBitmap;
    }

    public static String getTimeString(long t) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
        return sdf.format(new Date(t));
    }

    public static String getDateTimeString(long t) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(t));
    }

    // 聊天窗口时间显示
    public static String getDateTimeStringnoss(long t) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(new Date(t));
    }

    public static boolean netWorkAvailable(Context context) {
        try {
            ConnectivityManager nw = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = nw.getActiveNetworkInfo();
            return networkInfo != null;

        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }

    }

    public static boolean compareLastTime(long compareNum) {

        LogUtil.i("apptool lastTime", lastTime + "");
        LogUtil.i("apptool System.currentTimeMillis()",
                System.currentTimeMillis() + "");

        if (lastTime == 0) {
            lastTime = System.currentTimeMillis();
            return true;
        } else {
            if ((System.currentTimeMillis() - lastTime) <= (compareNum * 1000)) {
                lastTime = System.currentTimeMillis();
                return true;
            } else {
                lastTime = System.currentTimeMillis();
                return false;
            }

        }

    }


    public static String getDeviceId(Context context) {
        String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return android_id;

    }

    public static void startPhotoZoom(Activity context, Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        context.startActivityForResult(intent, RESULT_ZOOM);
    }

    /**
     * 基于余弦定理求两经纬度距离
     * 
     * @param lon1
     *            第一点的精度
     * @param lat1
     *            第一点的纬度
     * @param lon2
     *            第二点的精度
     * @param lat2
     *            第二点的纬度
     * @return 返回的距离，单位km
     * */
    public static String transformDistance(String lon1, String lat1,
            String lon2, String lat2) {

        double distance = getDistance(lon1, lat1, lon2, lat2);

        DecimalFormat df = new DecimalFormat("0.00");

        if (distance > 1000) {
            return df.format(distance / 1000) + "公里";
        } else {
            MathContext v = new MathContext(0, RoundingMode.HALF_DOWN);
            BigDecimal d = new BigDecimal(distance, v);
            return d.intValue() + "米";
        }

    }


    public static double getDistance(String lon11, String lat11, String lon22,
            String lat22) {

        double lon1 = Double.valueOf(lon11);
        double lat1 = Double.valueOf(lat11);
        double lon2 = Double.valueOf(lon22);
        double lat2 = Double.valueOf(lat22);

        double EARTH_RADIUS = 6378.137;
        double radLat1 = lat1 * Math.PI / 180.0;
        double radLat2 = lat2 * Math.PI / 180.0;
        double a = radLat1 - radLat2;
        double b = lon1 * Math.PI / 180.0 - lon2 * Math.PI / 180.0;

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10;

        return s;
    }

    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 获取APP版本号
     * @param context
     * @return
     */
    public static long getVersionCode(Context context) {
        long versionCode = 1;
        try {
            PackageInfo mPackageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                versionCode = mPackageInfo.getLongVersionCode();
            } else {
                versionCode = mPackageInfo.versionCode;
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本号名称
     * @param context 上下文
     * @return  返回版本号名称
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }


    /**
     * 获取App图标 bitmap
     * @param context   上下文
     * @return 返回App图标
     */
    public static synchronized Bitmap getBitmap(Context context) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getApplicationContext()
                    .getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(
                    context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            applicationInfo = null;
        }
        Drawable d = packageManager.getApplicationIcon(applicationInfo); //xxx根据自己的情况获取drawable
        BitmapDrawable bd = (BitmapDrawable) d;
        Bitmap bm = bd.getBitmap();
        return bm;
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context   上下文
     * @return 当前应用的包名称
     */
    public static synchronized String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static PackageInfo getSoftVersion(Context context) {
        PackageInfo mPackageInfo = null;
        try {
            mPackageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return mPackageInfo;
    }

    /**
     * 获取手机操作系统版本
     * 
     * @return
     */
    public static final int getSDKVersion() {
        int sdk = Build.VERSION.SDK_INT;
        return sdk;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 隐藏键盘
     */
    public static void hideKeyboard(Activity activity, View view) {
        // 隐藏键盘
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 获取屏幕宽度
     * 
     * @param activity
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static int getWidth(Activity activity) {
        int width = 0;
        if (AppTools.getSDKVersion() > 16) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point point = new Point();
            display.getRealSize(point);
            width = point.x;
        } else {
            width = activity.getWindowManager().getDefaultDisplay().getWidth();
        }
        return width;
    }

    /**
     * 获取屏幕高度
     * 
     * @param activity
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static int getHeight(Activity activity) {
        int height = 0;
        if (AppTools.getSDKVersion() > 16) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point point = new Point();
            display.getRealSize(point);
            height = point.y;
        } else {
            height = activity.getWindowManager().getDefaultDisplay()
                    .getHeight();
        }
        return height;
    }

    /**
     * 获取状态栏的高度
     * 
     * @param activity
     * @return
     */
    public static int getStatusHeight(Activity activity) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        activity.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass
                        .getField("status_bar_height").get(localObject)
                        .toString());
                statusHeight = activity.getResources()
                        .getDimensionPixelSize(i5);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

    /**
     * <获取手机本地IP地址>
     * @return: String [返回手机IP地址]
     * @exception: throws SocketException
     */
    public static final String getLocalIpAddress() throws SocketException {
        for (Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface info = en.nextElement();
            for (Enumeration<InetAddress> enAddr = info.getInetAddresses(); enAddr
                    .hasMoreElements();) {
                InetAddress addr = enAddr.nextElement();
                if (!addr.isLoopbackAddress()) {
                    String ip = addr.getHostAddress();
                    return ip;
                }
            }
        }
        return null;
    }

    /**
     * 去小数点后两位 四舍五入
     * 
     * @param f
     * @return
     */
    public static final double decimal(double f) {
        BigDecimal bg = new BigDecimal(f);
        return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    
    /**
     * 检查是apk包是否已安装到设备
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isAppInstalled(Context context,String packageName) {  
        PackageManager pm = context.getPackageManager();  
        boolean installed =false;  
        try {  
            pm.getPackageInfo(packageName,PackageManager.GET_ACTIVITIES);  
            installed =true;  
        } catch(NameNotFoundException e) {
            installed =false;  
        }  
        return installed;
    }  
    
    /**
     * 获取状态栏高度
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
      int result = 0;
      int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
      if (resourceId > 0) {
          result = context.getResources().getDimensionPixelSize(resourceId);
      }
      return result;
    }
    
    /**
     * 手机号校验
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^(1[345678][0-9]{9})|17[0-9]{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
    
    /**
     * 手机号隐藏
     * @param mobiles
     * @return
     */
    public static String hideMobile(String mobiles) {
    	String sub = mobiles.substring(3, 7);
    	mobiles = mobiles.replaceFirst(sub, "****");
        return mobiles;
    }
    
    /**
	 * 处理一个URL， 服务器返回过来的数据包含“\/” , 这里要替换成“/”。 如果服务器返回的URL正常，则不需要此方法处理
	 * 
	 * @param strUrl
	 *            需要处理的字符串
	 * @return 替换后的字符串
	 */
    public static String handlerUrl(String strUrl) {
		return strUrl.replaceAll("\\/", "/");
	}
    
    /**
     * app是否显示
     * @param context
     * @return
     */
    public static boolean isAppRunning(Context context){
    	ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(100);
		boolean isAppRunning = false;
		String MY_PKG_NAME = context.getPackageName();
		for (RunningTaskInfo info : list) {
			if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
				isAppRunning = true;
				break;
			}
		}
		return isAppRunning;
    }
}
